﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Furion.DatabaseAccessor.Extensions;
using iemtm.WeChat.Core.Extension;
using iemtm.WeChat.Core.Model;

namespace iemtm.WeChat.Core.Util
{
    public static class Common
    {
        public static Hashtable GetSettingValues(string keys, string prjcode , bool b2double = true)
        {
            Hashtable ht = new Hashtable();
            if (string.IsNullOrEmpty(keys))
                return ht;
            List<string> ls = keys.StringSplitTirm(",").ToList();
            if (ls == null || ls.Count <= 0)
                return ht;
            keys = (from ii in ls select "'" + ii + "'").ToList().StrListToStr(",");
           
            if (string.IsNullOrEmpty(prjcode))
                return ht;
            string sql = string.Format("SELECT * FROM dbo.ProjectSetting WHERE   ParaName IN ({0}) AND (PrjCode='{1}' OR PrjCode='01') ORDER BY PrjCode DESC", keys, prjcode);
            DataTable dt =(sql).SqlQuery();
            if (dt == null || dt.Rows.Count <= 0)
                return ht;
            foreach (DataRow dr in dt.Rows)
            {
                Object key = dr["ParaName"];
                object val = dr["ParaVal"];
                if (key != DBNull.Value && key.ToString() != "" && !ht.ContainsKey(key.ToString()))
                    ht[key.ToString()] = val == DBNull.Value ? "" : val.ToString();
            }
            if (b2double)
                ht = HashValueStr2Double(ht);
            return ht;
        }
        public static Hashtable HashValueStr2Double(Hashtable ht)
        {
            if (ht == null)
                return null;
            Hashtable htn = new Hashtable();
            IEnumerator en = ht.Keys.GetEnumerator();
            while (en.MoveNext())
            {
                double dtmp = double.NaN;
                if (ht[en.Current.ToString()] != null && Common.GetFirstDouble(ht[en.Current.ToString()].ToString(), ref dtmp))
                    htn[en.Current.ToString()] = dtmp;
                else
                    htn[en.Current.ToString()] = ht[en.Current.ToString()];
            }
            return htn;
        }

        public static bool GetFirstDouble(string str, ref double result)
        {
            string strTmp = GetNumStr(str, 0);
            if (strTmp != "")
            {
                result = double.Parse(strTmp);
                return true;
            }
            else
            {
                return false;
            }
        }
        public static string GetNumStr(String str, int idx)
        {
            string ss = "";
            bool bStart = false;
            for (int i = idx; i < str.Length; i++)
            {
                if (Char.IsNumber(str, i) == true || str[i] == '.')
                {
                    if (!bStart)
                        bStart = true;
                    ss += str.Substring(i, 1);
                }
                else
                {
                    if (bStart)
                        break;
                }
            }
            return ss;
        }

        /// <summary>
        /// 解析设备上传的经纬度信息
        /// </summary>
        /// <param name="gpsStr">设备上报的原始经纬度字符串</param>
        /// <param name="wendu">转换后的纬度</param>
        /// <param name="jingdu">转换后的经度</param>
        /// <returns>转换是否成功</returns>
        public static bool GetGPSWeiduAndJingdu660D(string gpsStr, ref decimal wendu, ref decimal jingdu)
        {
            try
            {
                string gps = gpsStr;
                if (gps != "")
                {
                    string[] strs = gps.Split(",".ToCharArray());
                    if (strs.Length < 3)
                    {
                        return false;
                    }
                    if (strs[0] == "0")
                        return false;
                    string strJingDu = "";
                    if (strs[1] != null && strs[1] != "")
                        strJingDu = strs[1].Replace("W", "-").Replace("E", "");
                    string strWeiDu = "";
                    if (strs[2] != null && strs[2] != "")
                        strWeiDu = strs[2].Replace("S", "-").Replace("N", "");
                    if (strWeiDu != "" && strJingDu != "")
                    {
                        if (decimal.TryParse(strWeiDu, out wendu) && decimal.TryParse(strJingDu, out jingdu))
                        {
                            wendu = (wendu / 100);
                            jingdu = (jingdu / 100);

                            wendu = (int)wendu + ((wendu - (int)wendu) * 100) / 60;
                            jingdu = (int)jingdu + ((jingdu - (int)jingdu) * 100) / 60;

                            return true;
                        }
                    }
                }
            }
            catch (Exception error)
            {
            }

            return false;
        }

        #region 微信推送
        /// <summary>
        /// 获取微信推送告警信息
        /// </summary>
        /// <param name="UserCode"></param>
        /// <returns></returns>
        public static AlarmCountModel GetPushAlarmCount(string UserCode)
        {
            AlarmCountModel model = new AlarmCountModel();
            DataTable Dt;
            //得到用户的属于区域
            DataTable dtAreaCode = ($"SELECT b.AreaCode FROM dbo.UserAccount a JOIN dbo.Company b ON	a.CompanyCode=b.CompanyCode WHERE a.UserCode='{UserCode}'").SqlQuery();
            var AreaCode = "";
            if (dtAreaCode.Rows.Count != 0)
                AreaCode = dtAreaCode.Rows[0]["AreaCode"].ToString();
            #region 退服
            Dt =($"SELECT COUNT(AlarmCode) AS	Count  FROM dbo.AlarmList WHERE AreaCode LIKE	'{AreaCode}%' AND AlarmType='退服' AND PrjCode='0113'").SqlQuery();
            if (Dt.Rows.Count > 0)
                model.OutServiceAmount = Convert.ToInt32(Dt.Rows[0]["Count"]);
            Dt = ($"SELECT COUNT(AlarmCode) AS	Count  FROM dbo.AlarmList WHERE AreaCode LIKE	'{AreaCode}%' AND AlarmType='退服' AND PrjCode='0113' AND	Operators LIKE '%移动%'").SqlQuery();
            if (Dt.Rows.Count > 0)
                model.OutServiceAmountByYD = Convert.ToInt32(Dt.Rows[0]["Count"]);
            Dt = ($"SELECT COUNT(AlarmCode) AS	Count  FROM dbo.AlarmList WHERE AreaCode LIKE	'{AreaCode}%' AND AlarmType='退服' AND PrjCode='0113' AND	Operators LIKE '%联通%'").SqlQuery();
            if (Dt.Rows.Count > 0)
                model.OutServiceAmountByLT = Convert.ToInt32(Dt.Rows[0]["Count"]);
            Dt = ($"SELECT COUNT(AlarmCode) AS	Count  FROM dbo.AlarmList WHERE AreaCode LIKE	'{AreaCode}%' AND AlarmType='退服' AND PrjCode='0113' AND	Operators LIKE '%电信%'").SqlQuery();
            if (Dt.Rows.Count > 0)
                model.OutServiceAmountByDX = Convert.ToInt32(Dt.Rows[0]["Count"]);
            #endregion
            #region 停电
            Dt = ($"SELECT COUNT(AlarmCode) AS	Count  FROM dbo.AlarmList WHERE AreaCode LIKE	'{AreaCode}%' AND AlarmType='停电' AND PrjCode='0113'").SqlQuery();
            if (Dt.Rows.Count > 0)
                model.MainsFailAmount = Convert.ToInt32(Dt.Rows[0]["Count"]);
            Dt = ($"SELECT COUNT(AlarmCode) AS	Count  FROM dbo.AlarmList WHERE AreaCode LIKE	'{AreaCode}%' AND AlarmType='停电' AND PrjCode='0113' AND	Operators LIKE '%移动%'").SqlQuery();
            if (Dt.Rows.Count > 0)
                model.MainsFailAmountByYD = Convert.ToInt32(Dt.Rows[0]["Count"]);
            Dt = ($"SELECT COUNT(AlarmCode) AS	Count  FROM dbo.AlarmList WHERE AreaCode LIKE	'{AreaCode}%' AND AlarmType='停电' AND PrjCode='0113' AND	Operators LIKE '%联通%'").SqlQuery();
            if (Dt.Rows.Count > 0)
                model.MainsFailAmountByLT = Convert.ToInt32(Dt.Rows[0]["Count"]);
            Dt = ($"SELECT COUNT(AlarmCode) AS	Count  FROM dbo.AlarmList WHERE AreaCode LIKE	'{AreaCode}%' AND AlarmType='停电' AND PrjCode='0113' AND	Operators LIKE '%电信%'").SqlQuery();
            if (Dt.Rows.Count > 0)
                model.MainsFailAmountByDX = Convert.ToInt32(Dt.Rows[0]["Count"]);
            #endregion
            #region FSU离线
            Dt = ($"SELECT COUNT(AlarmCode) AS	Count  FROM dbo.AlarmList WHERE AreaCode LIKE	'{AreaCode}%' AND AlarmType='FSU离线' AND PrjCode='0113'").SqlQuery();
            if (Dt.Rows.Count > 0)
                model.FSUAmount = Convert.ToInt32(Dt.Rows[0]["Count"]);
            Dt = ($"SELECT COUNT(AlarmCode) AS	Count  FROM dbo.AlarmList WHERE AreaCode LIKE	'{AreaCode}%' AND AlarmType='FSU离线' AND PrjCode='0113' AND	Operators LIKE '%移动%'").SqlQuery();
            if (Dt.Rows.Count > 0)
                model.FSUAmountByYD = Convert.ToInt32(Dt.Rows[0]["Count"]);
            Dt = ($"SELECT COUNT(AlarmCode) AS	Count  FROM dbo.AlarmList WHERE AreaCode LIKE	'{AreaCode}%' AND AlarmType='FSU离线' AND PrjCode='0113' AND	Operators LIKE '%联通%'").SqlQuery();
            if (Dt.Rows.Count > 0)
                model.FSUAmountByLT = Convert.ToInt32(Dt.Rows[0]["Count"]);
            Dt = ($"SELECT COUNT(AlarmCode) AS	Count  FROM dbo.AlarmList WHERE AreaCode LIKE	'{AreaCode}%' AND AlarmType='FSU离线' AND PrjCode='0113' AND	Operators LIKE '%电信%'").SqlQuery();
            if (Dt.Rows.Count > 0)
                model.FSUAmountByDX = Convert.ToInt32(Dt.Rows[0]["Count"]);
            #endregion
            #region 今日发电工单
            var TodayAnnCount = GetAlarmCountsByWXPush(UserCode, 1, "");
            model.TodayAnnouce = TodayAnnCount.noExtTotal + TodayAnnCount.exingTotal + TodayAnnCount.completelyTotal + TodayAnnCount.audiuTotal;
            model.TodayInAnnouce = TodayAnnCount.exingTotal;
            #endregion
            #region 半月发电工单
            var WeekAnnCount = GetAlarmCountsByWXPush(UserCode, 7, "");
            model.WeekAnnouce = WeekAnnCount.noExtTotal + WeekAnnCount.exingTotal + WeekAnnCount.completelyTotal + WeekAnnCount.audiuTotal;
            model.WeekOldAnnouce = WeekAnnCount.completelyTotal + WeekAnnCount.audiuTotal;
            #endregion
            #region 可用油机
            var GenCount = GetGenListByWXPush(5, UserCode);
            model.IdleAmount = Convert.ToInt32(GenCount);
            #endregion
            return model;
        }

        public static dynamic GetAlarmCountsByWXPush(string userCode, int times = 0, string paraStr = "")
        {
            UserAccount loginfo = GetUserAccount(userCode);
            if (loginfo == null)
                return null;
            var whereStr = 0;
            if (paraStr != "" && paraStr != null)
                whereStr = 1;//搜索框有内容
            var whereStr2 = (whereStr == 1) ? (" and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : "";
            if (times == 1)//今天
            {
                whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select CONVERT(varchar(30),GETDATE(),23)+' 00:00:00') and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select CONVERT(varchar(30),GETDATE(),23)+' 00:00:00') and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') ");
            }
            else if (times == 7)//7天内
            {
                whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select dateadd(day,-7,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select dateadd(day,-7,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') ");
                //whereStr2 = " and al.ExecutionDate>=(select dateadd(day,-7,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')";
            }
            //else if (times == 15)//半个月
            //{
            //    whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select dateadd(day,-15,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select dateadd(day,-15,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') ");
            //    //whereStr2 = " and al.ExecutionDate>=(select dateadd(day,-15,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')";
            //}
            else if (times == 30)//本月
            {
                whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select substring(CONVERT(varchar(30),GETDATE(),23),0,8)+'-01 00:00:00') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select substring(CONVERT(varchar(30),GETDATE(),23),0,8)+'-01 00:00:00') ");
                //whereStr2 = " and al.ExecutionDate>=(select substring(CONVERT(varchar(30),GETDATE(),23),0,8)+'-01 00:00:00') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')";
            }
            var isAudit = loginfo.PerUrls.Contains("/Gen/AnnounceTeleAudit/Audit");
            string sqlstr = "";
            string notExeDtsqlstr = "";
            //未执行的
            DataTable notExeDt;
            //获取执行中的通知单
            DataTable exeingDt;
            //获取执行完成的通知单
            DataTable completeDt;
            //获取审核通过或未通过的通知单
            DataTable audiuDt;
            var isOperaterView = false;
            if (isAudit && loginfo.RoleCode != "subadmin")//如果是运营商则只筛选跟他相关的工单
            {
                isOperaterView = true;
                var whereStr1 = "";
                if (loginfo.RoleCode == "ChinaMobileMonitor")
                {
                    whereStr1 = " and aa.GenerationForCompanyType = 4";
                }
                else if (loginfo.RoleCode == "ChinaUnicomMonitor")
                {
                    whereStr1 = " and aa.GenerationForCompanyType = 5";
                }
                else if (loginfo.RoleCode == "ChinaTelcomMonitor")
                {
                    whereStr1 = " and aa.GenerationForCompanyType = 6";
                }
                bool commonFilterJustByArea = loginfo.PerUrls.Contains("/DataPermission/CommonFilterJustByArea");
                string filterCompanyCode = " and al.areaCode like '" + loginfo.AreaCode + "%'";
                sqlstr = " SELECT COUNT(*) AS	count FROM (select al.AnnounceId,al.AnnounceCode,al.JobNumber,al.AreaCode,al.BaseStationID,al.BaseStation,al.GenerationFor," +
                          "(select username from UserAccount where usercode = al.AnnouncePerson) as AnnouncePerson,al.AcceptPersonCode,al.AcceptPersonName,al.RegisteredGenset,al.RegisteredAbnormal,al.GenManagePersonPhone," +
                          "al.ExecutionDate,AnnounceStatusValue = (select c.DicType from CommType c where c.TabName = 'AnnounceStatus' and c.DicValue =(select top 1 aa.AnnounceStatus from AnnounceAudit aa where aa.AnnounceCode=al.AnnounceCode " + whereStr1 + "))," +
                          "AnnounceStatus=(select top 1 aa.AnnounceStatus from AnnounceAudit aa where aa.AnnounceCode=al.AnnounceCode " + whereStr1 + "),aAnnounceId=(select top 1 aa.Id from AnnounceAudit aa where aa.AnnounceCode=al.AnnounceCode " + whereStr1 + ") from AnnounceList al  " +
                          "where al.prjcode=" + loginfo.PrjCode + " and al.AnnounceCode in(select distinct aa.AnnounceCode from AnnounceAudit aa where (aa.AnnounceStatus {0} " + whereStr1 + ")  " + filterCompanyCode + "" + whereStr2 + " ) AS T";

                //未执行的
                //notExeDt = new DataTable();
                notExeDt =("SELECT COUNT(AnnounceId) AS count FROM dbo.AnnounceList WHERE AnnounceStatus=1000").SqlQuery();//赋值0
                //获取执行中的通知单
                //exeingDt = new DataTable();
                exeingDt = ("SELECT COUNT(AnnounceId) AS count FROM dbo.AnnounceList WHERE AnnounceStatus=1000").SqlQuery();//赋值0

                //获取执行完成的通知单
                completeDt = (string.Format(sqlstr, "=29 or AnnounceStatus=31)")).SqlQuery();

                //获取审核通过或未通过的通知单
                audiuDt = (string.Format(sqlstr, "=30)")).SqlQuery();
            }
            else
            {
                isOperaterView = false;
                bool bTurnOrder = loginfo.PerUrls.Contains("/Gen/Announce/UserTurnOrder");
                bool bAllOrder = loginfo.PerUrls.Contains("/api/appservice/GetAnnounceLists");
                string areaFilterStr = GetAreaFilterStrWx(loginfo.AreaCode, loginfo);
                bool commonFilterJustByArea = loginfo.PerUrls.Contains("/DataPermission/CommonFilterJustByArea");
                string filterCompanyCode = commonFilterJustByArea ? areaFilterStr.Replace("(", " where al.").Replace(")", " ") : " where al.AcceptCompanyCode like '" + loginfo.CompanyCode + "%' ";

                sqlstr = "SELECT COUNT(*) AS	count FROM (select distinct '" + (bTurnOrder) + "' as bTurnOrder,al.AnnounceId,al.AnnounceCode,al.JobNumber,al.AreaCode,al.BaseStationID,al.BaseStation," +
                    "(select username from UserAccount where usercode=al.AnnouncePerson) as AnnouncePerson,al.AcceptPersonCode,al.AcceptPersonName,al.RegisteredGenset,al.RegisteredAbnormal," +
                    "al.GenManagePersonPhone,al.CreateDate as ExecutionDate,AnnounceStatusValue=(select c.DicType from CommType c where c.TabName='AnnounceStatus' and c.DicValue=al.AnnounceStatus)," +
                                  "al.AnnounceStatus from AnnounceList al " + (bAllOrder ? filterCompanyCode : "where (al.AcceptPersonCode='" + loginfo.UserCode + "')") + " and (al.AnnounceStatus{0}) " + "" + whereStr2 + "  ) AS T";
                string filterIsTieta = commonFilterJustByArea ? "al.AreaCode like '" + loginfo.AreaCode + "%'" : "al.AnnounceCode in (select AnnounceCode from AnnounceCompany where CompanyCode like '" + loginfo.CompanyCode + "%')";
                notExeDtsqlstr = "SELECT COUNT(*) AS	count FROM (select distinct al.AnnounceId,al.AnnounceCode,al.JobNumber,al.AreaCode,al.BaseStationID,al.BaseStation," +
             "(select username from UserAccount where usercode=al.AnnouncePerson) as AnnouncePerson,al.AcceptPersonCode,al.AcceptPersonName,al.RegisteredGenset,al.RegisteredAbnormal," +
             "al.GenManagePersonPhone,al.CreateDate as ExecutionDate,AnnounceStatusValue=(select c.DicType from CommType c where c.TabName='AnnounceStatus' and c.DicValue=al.AnnounceStatus),al.AnnounceStatus from AnnounceList al where " + filterIsTieta + " and (al.AnnounceStatus={0} " + whereStr2 + " ) AS T";
                //未执行的
                notExeDt = (string.Format(notExeDtsqlstr, "20 )")).SqlQuery();

                //获取执行中的通知单
                exeingDt =(string.Format(sqlstr, ">=21 and AnnounceStatus<=28 ")).SqlQuery();

                //获取执行完成的通知单
                completeDt =(string.Format(sqlstr, "=29 or AnnounceStatus=31")).SqlQuery();

                //获取审核通过或未通过的通知单
                audiuDt = (string.Format(sqlstr, "=30")).SqlQuery();

            }


            return new
            {
                isAudit = isAudit,
                isOperaterView = isOperaterView,
                noExtTotal = notExeDt.Rows[0]["count"],
               
                exingTotal = exeingDt.Rows[0]["count"],
               
                completelyTotal = completeDt.Rows[0]["count"],
             
                audiuTotal = audiuDt.Rows[0]["count"],
                
            };
        }

        public static dynamic GetGenListByWXPush(int rows, string userCode)
        {
            UserAccount loginfo = GetUserAccount(userCode);
            //List<Generator> genlist = BllHelper.gBuff.All.Values.Where(gen => gen.PrjCode == loginfo.prjCode && (gen.CompanyCode.StartsWith(loginfo.companyCode) || gen.AreaCode.StartsWith(loginfo.areaCode))).ToList();
            //项目筛选
            List<Generator> genlist0 =MemoryEntity.gBuffGen.All.Values.Where(gen => gen.PrjCode == loginfo.PrjCode).ToList();
            //区域筛选
            List<string> vas = loginfo.VisibleArea.StringSplitTirm(",").ToList();
            if (vas == null || vas.Count <= 0) genlist0 = null;
            List<Generator> genlist = new List<Generator>();
            if (genlist0 != null)
                foreach (Generator gg in genlist0)
                {
                    foreach (string ii in vas)
                        if (gg.AreaCode.StartsWith(ii)) { genlist.Add(gg); break; }
                }
            //公司筛选
            bool CommonFilterJustByArea = loginfo.PerUrls.Contains("/DataPermission/CommonFilterJustByArea");
            if (!CommonFilterJustByArea && genlist != null)
                genlist = genlist.Where(gen => gen.CompanyCode.StartsWith(loginfo.CompanyCode)).ToList();

            ComputeGensStatus(genlist);
            var s = from gen in genlist
                    orderby gen.BOnline descending
                    select new
                    {
                        GeneratorId = gen.GeneratorId,
                        BOnline = gen.BOnline,
                        Status = gen.Status,
                        ComputedStatus = gen.ComputedStatus,
                        GensetNum = gen.GensetNum,
                        name = gen.GensetNum,
                        label = gen.GensetNum,
                        DTUID = gen.DTUID ?? "0",//gen.DTUID,
                        IsIdle = gen.IsIdle,
                    };
            if (rows == 0)
            {
                return s.ToList().Count;
            }
            else if (rows == 1)
            {
                return s.Where(c => c.ComputedStatus == 1 && c.BOnline == true).ToList().Count;
            }
            else if (rows == 5)
            {
                return s.Where(c => c.ComputedStatus == 5).ToList().Count;
            }
            else if (rows == 3)
            {
                return s.Where(c => c.ComputedStatus == 3).ToList().Count;
            }
            return s;
        }


        /// <summary>
        /// 铁塔工单推送区域数量统计
        /// </summary>
        /// <returns></returns>
        public static List<TowerAnnounceAuditModel> GetTowerAnnounceAuditList()
        {
            List<TowerAnnounceAuditModel> statRtmp = new List<TowerAnnounceAuditModel>();
            string areaCode = "000100060001";
            string prjCode = "0113";
            //获取所有贵州省的子区域
            string sql = $"SELECT a.AreaCode,a.AreaName,a.ParentCode,a.Administrativelevel,b.AreaName as ParentName FROM dbo.Area a left join area b on a.parentcode=b.areacode WHERE  a.AreaCode like '{areaCode}%'";
            DataTable dtTmp = (sql).SqlQuery();
            if (dtTmp == null || dtTmp.Rows.Count <= 0)
                return null;
            Dictionary<string, TowerAnnounceAuditModel> stat = new Dictionary<string, TowerAnnounceAuditModel>();
            foreach (DataRow dr in dtTmp.Rows)
            {
                TowerAnnounceAuditModel a = new TowerAnnounceAuditModel();
                a.AreaCode = dr["AreaCode"].ToString();
                a.AreaName = dr["AreaName"].ToString();
                a.ParentCode = dr["ParentCode"].ToString();
                a.ParentName = dr["ParentName"].ToString();
                a.Level = dr["Administrativelevel"].ToString();

                if (!stat.ContainsKey(a.AreaCode))
                    stat.Add(a.AreaCode, a);
            }
            //确定需要被统计的区域
            List<TowerAnnounceAuditModel> statR = (from ii in stat.Values where !string.IsNullOrEmpty(ii.AreaCode) && (ii.AreaCode == areaCode || ii.ParentCode == areaCode) select ii).ToList();
            if (statR == null || statR.Count <= 0)
                return null;
            //确定当天铁塔需要审核工单数（当天）
            string start = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd ") + "00:00:00";
            string end = DateTime.Now.ToString("yyyy-MM-dd ") + "00:00:00";
            sql = $"SELECT AreaCode,AnnounceStatus FROM dbo.AnnounceList WHERE ExecutionDate>='{start}' AND ExecutionDate<'{end}' AND AreaCode LIKE '{areaCode}%' AND PrjCode='{prjCode}' AND (AnnounceStatus=29 OR AnnounceStatus=33 OR AnnounceStatus=34)";
            dtTmp = (sql).SqlQuery();
            if (dtTmp == null && dtTmp.Rows.Count == 0)
                return null;
            var jq = from t in dtTmp.AsEnumerable()
                     group t by new { tt = t.Field<string>("AreaCode") } into m
                     select new
                     {
                         AreaCode = m.Key.tt,
                         Count = m.Count()
                     };
            jq.ToList().ForEach(ii =>
            {
                if (stat.ContainsKey(ii.AreaCode))
                {
                    stat[ii.AreaCode].Count = ii.Count;
                }
            });
            //累加子区域的到父区域

            foreach (TowerAnnounceAuditModel ii in stat.Values)
            {
                TowerAnnounceAuditModel tt = MakeACopy(ii) as TowerAnnounceAuditModel;
                statRtmp.Add(tt); ;
                List<TowerAnnounceAuditModel> tmpa = (from kk in stat where kk.Value.AreaCode.StartsWith(ii.AreaCode) select kk.Value).ToList();
                if (tmpa != null && tmpa.Count > 0)
                {
                    tt.Count = tmpa.Sum(jj => jj.Count);
                }
            }
            return statRtmp.ToList();
        }

        /// <summary>
        /// 铁塔工单推送区域数量统计
        /// </summary>
        /// <returns></returns>
        public static List<OperatorAnnounceAuditModel> GetOperatorAnnounceAudit()
        {
            List<OperatorAnnounceAuditModel> statRtmp = new List<OperatorAnnounceAuditModel>();
            string areaCode = "000100060001";
            string prjCode = "0113";
            //获取所有贵州省的子区域
            string sql = $"SELECT a.AreaCode,a.AreaName,a.ParentCode,a.Administrativelevel,b.AreaName as ParentName FROM dbo.Area a left join area b on a.parentcode=b.areacode WHERE  a.AreaCode like '{areaCode}%'";
            DataTable dtTmp = (sql).SqlQuery();
            if (dtTmp == null || dtTmp.Rows.Count <= 0)
                return null;
            Dictionary<string, OperatorAnnounceAuditModel> stat = new Dictionary<string, OperatorAnnounceAuditModel>();
            foreach (DataRow dr in dtTmp.Rows)
            {
                OperatorAnnounceAuditModel a = new OperatorAnnounceAuditModel();
                a.AreaCode = dr["AreaCode"].ToString();
                a.AreaName = dr["AreaName"].ToString();
                a.ParentCode = dr["ParentCode"].ToString();
                a.ParentName = dr["ParentName"].ToString();
                a.Level = dr["Administrativelevel"].ToString();

                if (!stat.ContainsKey(a.AreaCode))
                    stat.Add(a.AreaCode, a);
            }
            //确定需要被统计的区域
            List<OperatorAnnounceAuditModel> statR = (from ii in stat.Values where !string.IsNullOrEmpty(ii.AreaCode) && (ii.AreaCode == areaCode || ii.ParentCode == areaCode) select ii).ToList();
            if (statR == null || statR.Count <= 0)
                return null;
            //确定当天铁塔需要审核工单数（当天）
            string start = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd ") + "00:00:00";
            string end = DateTime.Now.ToString("yyyy-MM-dd ") + "00:00:00";
            sql = $"SELECT b.AreaCode,a.GenerationForCompanyType,a.AnnounceStatus FROM dbo.AnnounceAudit a LEFT JOIN dbo.AnnounceList b ON a.AnnounceCode=b.AnnounceCode WHERE b.ExecutionDate>='{start}' AND b.ExecutionDate<'{end}' AND b.AreaCode LIKE '{areaCode}%' AND b.PrjCode='{prjCode}' AND a.AnnounceStatus=29";
            dtTmp = (sql).SqlQuery();
            if (dtTmp == null && dtTmp.Rows.Count == 0)
                return null;
            var jq = from t in dtTmp.AsEnumerable()
                     group t by new { tt = t.Field<string>("AreaCode") } into m
                     select new
                     {
                         AreaCode = m.Key.tt,
                         MobileCount = m.Count(ii => ii.Field<int>("GenerationForCompanyType") == 4),
                         UnicomCount = m.Count(ii => ii.Field<int>("GenerationForCompanyType") == 5),
                         TelecomCount = m.Count(ii => ii.Field<int>("GenerationForCompanyType") == 6),
                     };
            jq.ToList().ForEach(ii =>
            {
                if (stat.ContainsKey(ii.AreaCode))
                {
                    stat[ii.AreaCode].MobileCount = ii.MobileCount;
                    stat[ii.AreaCode].UnicomCount = ii.UnicomCount;
                    stat[ii.AreaCode].TelecomCount = ii.TelecomCount;
                }
            });
            //累加子区域的到父区域

            foreach (OperatorAnnounceAuditModel ii in stat.Values)
            {
                OperatorAnnounceAuditModel tt = MakeACopy(ii) as OperatorAnnounceAuditModel;
                statRtmp.Add(tt); ;
                List<OperatorAnnounceAuditModel> tmpa = (from kk in stat where kk.Value.AreaCode.StartsWith(ii.AreaCode) select kk.Value).ToList();
                if (tmpa != null && tmpa.Count > 0)
                {
                    tt.MobileCount = tmpa.Sum(jj => jj.MobileCount);
                    tt.UnicomCount = tmpa.Sum(jj => jj.UnicomCount);
                    tt.TelecomCount = tmpa.Sum(jj => jj.TelecomCount);
                }
            }
            return statRtmp.ToList();
        }
        #endregion

        public static UserAccount GetUserAccount(string UserCode)
        {
            string gerUserSql = @"select ua.*,r.RoleName,c.CompanyName,a.AreaCode,a.AreaName,p.PrjName from UserAccount ua
                            left Join [Role] r on r.RoleCode=ua.RoleCode
                            left Join Company c on c.CompanyCode=ua.CompanyCode
                            left Join Area a on a.AreaCode=c.AreaCode
                            left Join Project p on p.PrjCode=ua.PrjCode
                             where ua.UserCode=@UserCode";
            var userInfos = gerUserSql.SqlQuery<UserAccount>(new { UserCode = UserCode });
            if (userInfos != null && userInfos.Count > 0)
            {
                string Perurl = "SELECT a.MenuCode,b.URL FROM dbo.Permission a LEFT JOIN dbo.MenuItem b ON b.MenuCode = a.MenuCode WHERE a.RoleCode=@RoleCode";
                var dtPer = Perurl.SqlQuery(new { RoleCode = userInfos[0].RoleCode });
                if (dtPer != null && dtPer.Rows.Count > 0)
                {
                    userInfos[0].PerCodes = (from t in dtPer.AsEnumerable() select t.Field<string>("MenuCode")).ToList();
                    userInfos[0].PerUrls = (from t in dtPer.AsEnumerable() select t.Field<string>("URL")).ToList();
                }
                else
                {
                    userInfos[0].PerCodes = new List<string>();
                    userInfos[0].PerUrls = new List<string>();
                }
                return userInfos[0];
            }
            else
            {
                return null;
            }
        }




        /// <summary>
        /// 对油机状态根据优先级进行状态合并
        /// 无采集器>运行中>需维修>需保养>正常
        /// </summary>
        /// <param name="gens"></param>
        public static void ComputeGensStatus(List<Generator> gens)
        {

            foreach (Generator gen in gens)
            {
                //运行中
                if ((gen.bRunning != null && gen.bRunning.Value) || gen.Status == 1)
                {
                    gen.ComputedStatus = 1;
                }
                //无采集器
                else if (string.IsNullOrEmpty(gen.DTUID) || gen.Status == 2)
                {
                    gen.ComputedStatus = 2;
                }
                //需维修
                else if ((gen.NeedRepaired != null && gen.NeedRepaired.Value) || gen.Status == 3)
                {
                    gen.ComputedStatus = 3;
                }
                //需保养    
                else if (gen.NeedMaintenance == true || gen.Status == 4)
                {
                    gen.ComputedStatus = 4;
                }
                //正常
                else
                {
                    gen.ComputedStatus = 5;
                }
            }
        }

        /// <summary>
        /// 用户可见区域过滤
        /// </summary>
        /// <param name="selAreaCode"></param>
        /// <param name="logininfo"></param>
        /// <param name="tablePrex"></param>
        /// <returns></returns>
        public static string GetAreaFilterStrWx(string selAreaCode, UserAccount logininfo, string tablePrex = "")
        {

            //用户可见区域过滤
            List<string> visibleArea = logininfo.VisibleArea.StringSplitTirm(",").ToList();
            if (visibleArea == null || visibleArea.Count <= 0)
                return null;
            //用户选择区域过滤
            List<string> visibleAreaSql = (from ii in visibleArea where selAreaCode.StartsWith(ii) select tablePrex + "AreaCode like '" + selAreaCode + "%'").Distinct().ToList();
            if (visibleAreaSql == null || visibleAreaSql.Count <= 0)
                visibleAreaSql = (from ii in visibleArea where ii.StartsWith(selAreaCode) select tablePrex + "AreaCode like '" + ii + "%'").ToList();
            if (visibleAreaSql == null || visibleAreaSql.Count <= 0)
                return null;
            return "(" + visibleAreaSql.StrListToStr(" or ") + ")";
        }

        /// <summary>
        /// 获取微信推送-人员信息
        /// </summary>
        /// <returns></returns>
        public static List<UserCompanyModel> GetWxUserCompanyModel()
        {
            string sql = @"select u.UserCode,u.RoleCode,c.AreaCode from UserAccount as u
                                    left join Company as c on u.CompanyCode=c.CompanyCode
                                    where u.RoleCode='subadmin'
                                    and u.WxOpenId is not null
                                    and u.PrjCode='0113'";
            var userList = sql.SqlQuery<UserCompanyModel>();
            return userList;
        }

        public static object MakeACopy(object obj)
        {
            Type t = obj.GetType();
            object nObj = Activator.CreateInstance(t);

            FieldInfo[] fields = t.GetFields();

            for (int i = 0; i < fields.Length; i++)
            {
                fields[i].SetValue(nObj, fields[i].GetValue(obj));
            }

            PropertyInfo[] pps = t.GetProperties();

            for (int i = 0; i < pps.Length; i++)
            {
                if (pps[i].Name == "Item")
                    continue;
                pps[i].SetValue(nObj, pps[i].GetValue(obj, null), null);
            }


            return nObj;
        }
    }
}
